package com.edouardbataille.open.sender
{
	import com.edouardbataille.open.MySqlSocket;
	import com.edouardbataille.open.handler.IHandler;
	import com.edouardbataille.open.result.ResultSet;
	
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
	
	import mx.core.mx_internal;
	import mx.managers.CursorManager;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	[Event (name="fault", type="mx.rpc.events.FaultEvent")]
	[Event (name="result", type="mx.rpc.events.ResultEvent")]
	public class Sender extends EventDispatcher
	{
		private var actualResponse : ByteArray;
		
		protected var con : MySqlSocket;
		
		private var numPacket : int = -1
		
		protected var _lastResult : ResultSet;
		
		protected var token : AsyncToken;
		
		private var _handler : IHandler;
		
		protected var queryStr : String;
		
		public var showBusyCursor : Boolean = false;
		
		protected function set handler (value : IHandler) : void
		{
			_handler = value;
			_handler.addEventListener(ResultEvent.RESULT, dispatchResult);
			_handler.addEventListener(FaultEvent.FAULT, dispatchFault);
		}
		
		protected function get handler () : IHandler
		{
			return _handler;
		}
		
		public function get lastResult () : ResultSet
		{
			return _lastResult;
		}

		public function Sender(con : MySqlSocket)
		{
			this.con = con
		}
		
		protected function send (ba : ByteArray, numPacket : int = 0) : void
		{
			actualResponse = ba;
			if (this.numPacket == -1)
				this.numPacket = numPacket
			con.send(actualResponse, handler, this.numPacket);
			numPacket = -1;
			actualResponse = null;
		}
		
		protected function dispatchResult (event : ResultEvent) : void
		{
			if (showBusyCursor)
				CursorManager.removeBusyCursor();
			_lastResult = event.result as ResultSet;
			var e: ResultEvent = ResultEvent.createEvent(_lastResult, token);
			dispatchEvent(e);
			token = null;
			e.mx_internal::callTokenResponders ();
		}
		
		protected function dispatchFault (event : FaultEvent) : void
		{
			if (showBusyCursor)
				CursorManager.removeBusyCursor();
			var e : FaultEvent = FaultEvent.createEvent(event.fault, token);
			dispatchEvent(e);
			token = null;
			e.mx_internal::callTokenResponders ();
		}
	}
}